package org.han.org.service.impl;

import org.han.base.service.impl.BaseServiceImpl;
import org.han.org.domain.Department;
import org.han.org.mapper.DepartmentMapper;
import org.han.org.service.IDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Resource
    private DepartmentMapper mapper;

    @Transactional
    @Override
    public void insert(Department department) {
        department.setCreate_time(new Date());// 设置新增时间
        mapper.insert(department);
        Department parent = department.getParent(); //获取前端过来的父部门
        String path;
        if(Objects.isNull(parent) || Objects.isNull(parent.getId())){
            path = "/" + department.getId();
        }else {
            parent = mapper.selectById(parent.getId());// 根据父部门的id，查询父部门的信息
            path = parent.getPath() + "/" + department.getId();// 父部门存在，该新增部门path = 父部门的path+"/"+自己的id
        }
        // 将path赋值给department
        department.setPath(path);
        // 修改
        mapper.update(department);
    }


    @Transactional
    @Override
    public void update(Department department) {
        department.setUpdate_time(new Date()); // 设置修改时间
        String path;
        // 判断父部门是否存在
        if(Objects.isNull(department.getParent())){
            //不存在
            path = "/" + department.getId();
        }else {
            // 存在查询父部门的部门
            Department parent = mapper.selectById(department.getParent().getId());
            path = parent.getPath()+ "/" +department.getId();
        }
        department.setPath(path);
        mapper.update(department);

    }

    @Override
    public List<Department> tree() {
        return mapper.tree();
    }
}
